package com.keray.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.common.model.NoDisturbPayload;
import cn.jmessage.api.common.model.RegisterInfo;
import cn.jmessage.api.common.model.UserPayload;
import cn.jmessage.api.common.model.friend.FriendNote;
import cn.jmessage.api.common.model.message.MessageBody;
import cn.jmessage.api.group.CreateGroupResult;
import cn.jmessage.api.group.GroupInfoResult;
import cn.jmessage.api.group.GroupListResult;
import cn.jmessage.api.group.MemberListResult;
import cn.jmessage.api.message.MessageType;
import cn.jmessage.api.message.SendMessageResult;
import cn.jmessage.api.resource.DownloadResult;
import cn.jmessage.api.resource.ResourceClient;
import cn.jmessage.api.resource.UploadResult;
import cn.jmessage.api.sensitiveword.SensitiveWordClient;
import cn.jmessage.api.sensitiveword.SensitiveWordListResult;
import cn.jmessage.api.sensitiveword.SensitiveWordStatusResult;
import cn.jmessage.api.user.*;
import cn.jpush.api.push.PushClient;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.push.model.notification.PlatformNotification;
import cn.jpush.api.report.MessagesResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author huangpeng
 * @Description //TODO
 * @Date 2021/10/19 14:46
 **/
@Slf4j
@Service
@ConditionalOnBean(JiGuangConfig.class)
@Data
public class JiGuangPlugin {

    private final JMessageClient messageClient;
    private final ResourceClient resourceClient;
    private final UserClient userClient;
    private final PushClient pushClient;
    private static final String baseUrl = "https://vip-langrun-middle-cdn.oss-accelerate.aliyuncs.com/";
    private final SensitiveWordClient sensitiveWordClient;
    private final JiGuangConfig jiGuangConfig;
    private final String appKey;

    public JiGuangPlugin(JiGuangConfig jiGuangConfig) {
        super();
        this.jiGuangConfig = jiGuangConfig;
        this.appKey = jiGuangConfig.getAppkey();
        messageClient = getMessageClient(jiGuangConfig.getAppkey(), jiGuangConfig.getMasterSecret());
        resourceClient = getResourceClient(jiGuangConfig.getAppkey(), jiGuangConfig.getMasterSecret());
        pushClient = getPushClient(jiGuangConfig.getAppkey(), jiGuangConfig.getMasterSecret());
        sensitiveWordClient = getSensitiveWordClient(jiGuangConfig.getAppkey(), jiGuangConfig.getMasterSecret());
        userClient = getUserClient(jiGuangConfig.getAppkey(), jiGuangConfig.getMasterSecret());
    }


    public String getToken(String appkey, String masterSecret) {
        return ServiceHelper.getBasicAuthorization(appkey, masterSecret);
    }

    public String getToken() {
        return getToken(jiGuangConfig.getAppkey(), jiGuangConfig.getMasterSecret());
    }

    public JMessageClient getMessageClient(String appkey, String masterSecret) {
        return new JMessageClient(appkey, masterSecret);
    }

    public ResourceClient getResourceClient(String appkey, String masterSecret) {
        return new ResourceClient(appkey, masterSecret);
    }

    public SensitiveWordClient getSensitiveWordClient(String appkey, String masterSecret) {
        return new SensitiveWordClient(appkey, masterSecret);
    }

    public PushClient getPushClient(String appkey, String masterSecret) {
        return new PushClient(masterSecret, appkey);
    }
    public UserClient getUserClient(String appkey, String masterSecret) {
        return new UserClient(masterSecret, appkey);
    }


    //*********************************用户管理**********************************************************

    /**
     * @return java.lang.String
     * @Param: []
     * @Author: huangpeng
     * @Date: 2021/10/19 14:55
     * @Description: 批量用户注册, 最多500
     */
    public String batchAddUser(List<RegisterInfo> users) {
        String result;
        RegisterInfo[] regUsers = new RegisterInfo[users.size()];
        try {
            result = messageClient.registerUsers(users.toArray(regUsers));
        } catch (Exception e) {
            log.error("极光用户注册异常:{}", e.getMessage());
//            throw new RuntimeException("极光用户注册异常:"+e.getMessage());
            return null;
        }
        return result;
    }
    public String addAdminuser(RegisterInfo payload) {
        String result;
        try {
            result = userClient.registerAdmins(payload).responseContent;
        } catch (Exception e) {
            log.error("极光用户注册异常:{}", e.getMessage());
//            throw new RuntimeException("极光用户注册异常:"+e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return cn.jmessage.api.user.UserInfoResult
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/19 16:01
     * @Description: 获取用户信息
     */
    public UserInfoResult getUserInfo(String userId) {
        UserInfoResult userInfo;
        try {
            userInfo = messageClient.getUserInfo(userId);
        } catch (Exception e) {
            log.error("极光用户信息异常:{}", e.getMessage());
            return null;
        }
        return userInfo;
    }

    /**
     * @return cn.jmessage.api.user.UserStateResult
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/19 16:06
     * @Description: 获取用户状态
     */
    public UserStateResult getUserState(String userId) {
        UserStateResult userState;
        try {
            userState = messageClient.getUserState(userId);
        } catch (Exception e) {
            log.error("极光用户状态异常:{}", e.getMessage());
            return null;
        }
        return userState;
    }

    /**
     * @return cn.jmessage.api.user.UserStateResult
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/19 16:07
     * @Description: 批量获取用户状态
     */
    public List<UserStateListResult> batchGetUsersState(List<String> userIds) {
        List<UserStateListResult> userState;
        try {
            userState = Arrays.asList(messageClient.getUsersState(userIds.toArray(new String[userIds.size()])));
        } catch (Exception e) {
            log.error("极光用户状态异常:{}", e.getMessage());
            return null;
        }
        return userState;
    }

    /**
     * @return void
     * @Param: [userId, newPassword]
     * @Author: huangpeng
     * @Date: 2021/10/19 16:57
     * @Description: 修改用户密码
     */
    public void updatePassword(String userId, String newPassword) {
        try {
            messageClient.updateUserPassword(userId, newPassword);
        } catch (Exception e) {
            log.error("极光修改用户密码异常:{}", e.getMessage());
        }
    }

    /**
     * @return void
     * @Param: [userId, userPayload]
     * @Author: huangpeng
     * @Date: 2021/10/19 16:57
     * @Description: 修改用户信息
     */
    public void updateUserInfo(String userId, UserPayload userPayload) {
        try {
            messageClient.updateUserInfo(userId, userPayload);
        } catch (Exception e) {
            log.error("极光修改用户信息异常:{}", e.getMessage());
        }
    }

    /**
     * @return cn.jmessage.api.user.UserListResult
     * @Param: [pageNo, pageSize]
     * @Author: huangpeng
     * @Date: 2021/10/19 16:59
     * @Description: 分页获取用户信息  从1开始
     */
    public UserListResult getUsersPage(Integer pageNo, Integer pageSize) {
        UserListResult userList;
        try {
            userList = messageClient.getUserList(pageSize * (pageNo - 1), pageSize);
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return userList;
    }

    /**
     * @return void
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:00
     * @Description: 删除用户
     */
    public void deleteUser(String userId) {
        try {
            messageClient.deleteUser(userId);
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
        }
    }

    /**
     * @return cn.jmessage.api.user.UserListResult
     * @Param: [pageNo, pageSize]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:05
     * @Description: 分页获取管理员
     */
    public UserListResult getAdminPage(Integer pageNo, Integer pageSize) {
        UserListResult result;
        try {
            result = messageClient.getAdminListByAppkey(pageSize * (pageNo - 1), pageSize);
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return java.util.List<cn.jmessage.api.user.UserInfoResult>
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:08
     * @Description: 获取用户黑名单
     */
    public List<UserInfoResult> getBlackList(String userId) {
        List<UserInfoResult> result;
        try {
            result = Arrays.asList(messageClient.getBlackList(userId));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return void
     * @Param: [userId, blackUserIds]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:12
     * @Description: 移除黑名单
     */
    public ResponseWrapper removeBlacklist(String userId, List<String> blackUserIds) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.removeBlacklist(userId, blackUserIds.toArray(new String[blackUserIds.size()]));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    /**
     * @return void
     * @Param: [userId, blackUserIds]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:14
     * @Description: 添加黑名单
     */
    public ResponseWrapper addBlackList(String userId, List<String> blackUserIds) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.addBlackList(userId, blackUserIds.toArray(new String[blackUserIds.size()]));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [userId, payload]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:21
     * @Description: 设置免打扰
     */
    public ResponseWrapper setNoDisturb(String userId, NoDisturbPayload payload) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.setNoDisturb(userId, payload);
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [userId, friendIds]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:23
     * @Description: 添加好友
     */
    public ResponseWrapper addFriends(String userId, List<String> friendIds) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.addFriends(userId, friendIds.toArray(new String[friendIds.size()]));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [userId, friendIds]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:24
     * @Description: 删除好友
     */
    public ResponseWrapper deleteFriends(String userId, List<String> friendIds) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.deleteFriends(userId, friendIds.toArray(new String[friendIds.size()]));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [userId, friendNotes]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:26
     * @Description: 修改好友备注
     */
    public ResponseWrapper updateFriendsNote(String userId, List<FriendNote> friendNotes) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.updateFriendsNote(userId, friendNotes.toArray(new FriendNote[friendNotes.size()]));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    /**
     * @return java.util.List<cn.jmessage.api.user.UserInfoResult>
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:28
     * @Description: 获取用户列表
     */
    public List<UserInfoResult> getFriends(String userId) {
        List<UserInfoResult> result;
        try {
            result = Arrays.asList(messageClient.getFriendsInfo(userId));
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [userId, disabled]
     * @Author: huangpeng
     * @Date: 2021/10/19 17:31
     * @Description: 禁用/启用 用户
     */
    public ResponseWrapper forbidUser(String userId, Boolean disabled) {
        ResponseWrapper responseWrapper;
        try {
            responseWrapper = messageClient.forbidUser(userId, disabled);
        } catch (Exception e) {
            log.error("极光接口异常:{}", e.getMessage());
            return null;
        }
        return responseWrapper;
    }

    //******************************群管理************************************************************

    /**
     * @return cn.jmessage.api.group.CreateGroupResult
     * @Param: [owner, gname, desc, avatar, flag, userlist]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:07
     * @Description: 创建群   desc也不能为空
     */
    public CreateGroupResult addGroup(String owner, String gname, String desc, String avatar, Integer flag, List<String> userlist) {
        if (StrUtil.isBlank(desc)) {
            desc = gname;
        }
        CreateGroupResult result;
        try {
            if (CollUtil.isEmpty(userlist)) {
                result = messageClient.createGroup(owner, gname, desc, avatar, null == flag ? 1 : flag);
            } else {
                result = messageClient.createGroup(owner, gname, desc, avatar, null == flag ? 1 : flag, userlist.toArray(new String[userlist.size()]));
            }
        } catch (Exception e) {
            log.error("极光接口创建群异常:{}", e.getMessage());
            throw new RuntimeException("极光创建群异常");
        }
        return result;
    }

    /**
     * @return cn.jmessage.api.group.GroupInfoResult
     * @Param: [groupId]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:07
     * @Description: 获取群信息
     */
    public GroupInfoResult getGroupInfo(Long groupId) {
        GroupInfoResult result;
        try {
            result = messageClient.getGroupInfo(groupId);
        } catch (Exception e) {
            log.error("极光接口获取群信息异常:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return cn.jmessage.api.group.MemberListResult
     * @Param: [groupId]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:07
     * @Description: 获取群成员
     */
    public MemberListResult getGroupMemberList(Long groupId) {
        MemberListResult result;
        try {
            result = messageClient.getGroupMembers(groupId);
        } catch (Exception e) {
            log.error("极光接口获取群成员异常:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return cn.jmessage.api.group.GroupListResult
     * @Param: [pageNo, pageSize]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:07
     * @Description: 分页获取群信息
     */
    public GroupListResult getGroupPage(Integer pageNo, Integer pageSize) {
        GroupListResult result;
        try {
            result = messageClient.getGroupListByAppkey(pageSize * (pageNo - 1), pageSize);
        } catch (Exception e) {
            log.error("极光接口获取群分页异常:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return void
     * @Param: [groupId, addList, removeList]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:10
     * @Description: 群管理  添加/移除用户
     */
    public void manageGroup(Long groupId, String[] addList, String[] removeList) {
        try {
            messageClient.addOrRemoveMembers(groupId, addList, removeList);
        } catch (Exception e) {
            log.error("极光接口管理群异常:{}", e.getMessage());
        }
    }

    /**
     * @return void
     * @Param: [groupId, groupName, groupDesc, avatar]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:11
     * @Description: 修改群信息
     */
    public void updateGroupInfo(Long groupId, String groupName, String groupDesc, String avatar) {
        try {
            messageClient.updateGroupInfo(groupId, groupName, groupDesc, avatar);
        } catch (Exception e) {
            log.error("极光接口管理群异常:{}", e.getMessage());
            throw new RuntimeException("极光群信息修改失败");
        }
    }

    /**
     * @return cn.jmessage.api.user.UserGroupsResult
     * @Param: [userId]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:14
     * @Description: 获取用户的群
     */
    public UserGroupsResult getGroupsByUser(String userId) {
        UserGroupsResult result;
        try {
            result = messageClient.getGroupListByUser(userId);
        } catch (Exception e) {
            log.error("极光接口用户群异常:{}", e.getMessage());
            throw new RuntimeException("获取用户联调群信息异常");
        }
        return result;
    }

    /**
     * @return void
     * @Param: [groupId]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:15
     * @Description: 删除群
     */
    public void deleteGroup(Long groupId) {
        try {
            messageClient.deleteGroup(groupId);
        } catch (Exception e) {
            log.error("极光接口删除群异常:{}", e.getMessage());
//            throw new RuntimeException("极光群删除异常");
        }
    }

    //******************************资源上传 获取mediaId*********************************

    /**
     * @return cn.jmessage.api.resource.UploadResult
     * @Param: [path, fileType]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:32
     * @Description: 上传文件
     */
    public UploadResult uploadFile(String path, String fileType) {
        UploadResult result;
        try {
            result = resourceClient.uploadFile(path, fileType);
        } catch (Exception e) {
            log.error("极光接口文件上传失败:{}", e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @return java.lang.String
     * @Param: [path, fileType]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:32
     * @Description: 上传文件  返回mediaId
     */
    public String uploadFileMediaId(String path, String fileType) {
        String mediaId;
        try {
            UploadResult uploadResult = resourceClient.uploadFile(path, fileType);
            mediaId = uploadResult.getMediaId();
        } catch (Exception e) {
            log.error("极光接口文件上传失败:{},path:{},fileType:{}", e.getMessage(), path, fileType);
            return null;
        }
        //删除本地图片
        File file = new File(path);
        file.delete();
        return mediaId;
    }

    /**
     * @return java.lang.String
     * @Param: [mediaId]
     * @Author: huangpeng
     * @Date: 2021/10/20 10:32
     * @Description: 下载文件 url
     */
    public String downloadFileurl(String mediaId) {
        String url;
        try {
            DownloadResult downloadResult = resourceClient.downloadFile(mediaId);
            url = downloadResult.getUrl();
        } catch (Exception e) {
            log.error("极光接口文件上传失败:{}", e.getMessage());
            return null;
        }
        return url;
    }

    /**
     * @return cn.jmessage.api.resource.DownloadResult
     * @Param: 下载文件
     * @Author: huangpeng
     * @Date: 2021/10/20 11:22
     * @Description:
     */
    public DownloadResult downloadFile(String mediaId) {
        DownloadResult result;
        try {
            result = resourceClient.downloadFile(mediaId);

        } catch (Exception e) {
            log.error("极光接口文件上传失败:{}", e.getMessage());
            return null;
        }
        return result;
    }

    public String uploadImgByUrl(String url) {
        if (StrUtil.isBlank(url)) {
            return null;
        }
        if (!url.startsWith("http")) {
            url = jiGuangConfig.getImgUrl() + url;
        }
        String path = jiGuangConfig.getImgPath() + url.substring(url.lastIndexOf("/"));
        URL url1 = null;
        try {
            url1 = new URL(url);
            DataInputStream dataInputStream = new DataInputStream(url1.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            log.error("文件下载异常:{}", e.getMessage());
        }
        return this.uploadFileMediaId(path, "image");
    }

    //*********************************极光推送**********************************************************
    public void packJpush(Map<String, String> map, String registrationId, List<String> tags, Boolean broadcast, Boolean noticeOrMessage) {
        // 极光推送指定用户用registrationId；学校推送按tags（tags需要前端在app用户注册极光时，加上学校code作为tags）或者是
        // “registration_id 值超过 1000 个，可以直接使用 文件推送 功能”；全体成员推送使用广播，


        PushPayload.Builder pushBuilder = PushPayload.newBuilder()
                .setPlatform(Platform.all());
        if (noticeOrMessage) {
            String content = map.get("content");
            Notification notification = Notification.newBuilder().setAlert(content)
                    .addPlatformNotification(AndroidNotification.newBuilder().setTitle(map.get("title")).addExtras(map).build())
                    .addPlatformNotification(IosNotification.newBuilder().addExtras(map).build())
                    .build();
            pushBuilder.setNotification(notification);

        } else {
            Message message = Message.newBuilder().setTitle(map.get("title")).setMsgContent(map.get("content")).addExtras(map).build();
            pushBuilder.setMessage(message);
        }

        if (registrationId!=null&&registrationId.length()>0) {
            pushBuilder.setAudience(Audience.alias(registrationId));
        }else if(CollUtil.isNotEmpty(tags)){
            pushBuilder.setAudience(Audience.tag(tags));
        }else if(broadcast){
            pushBuilder.setAudience(Audience.all());
        }
        PushPayload pushPayload = pushBuilder.build();
        try {
            pushClient.sendPush(pushPayload);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    public void sendJPush(Map<String, String> map, List<String> alias, List<String> tags, Boolean noticeOrMessage) {


        PushPayload.Builder pushBuilder = PushPayload.newBuilder()
                .setPlatform(Platform.all());
        if (noticeOrMessage) {
            String content = map.get("content");
            Notification notification = Notification.newBuilder().setAlert(content)
                    .addPlatformNotification(AndroidNotification.newBuilder().setTitle(map.get("title")).addExtras(map).build())
                    .addPlatformNotification(IosNotification.newBuilder().addExtras(map).build())
                    .build();
            pushBuilder.setNotification(notification);

        } else {
            Message message = Message.newBuilder().setTitle(map.get("title")).setMsgContent(map.get("content")).addExtras(map).build();
            pushBuilder.setMessage(message);
        }
        if (CollUtil.isNotEmpty(alias)) {
                  pushBuilder.setAudience(Audience.alias(alias));
        }else if(CollUtil.isNotEmpty(tags)){
            pushBuilder.setAudience(Audience.tag(tags));
        }else {
            pushBuilder.setAudience(Audience.all());
        }
        PushPayload pushPayload = pushBuilder.build();
        try {
            pushClient.sendPush(pushPayload);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }



    //******************************敏感词管理*********************************

    /*
     * @Param: [words]
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Author: huangpeng
     * @Date: 2021/10/25 10:12
     * @Description: 批量添加敏感词
     */
    public ResponseWrapper addSensitiveWords(List<String> words) {
        ResponseWrapper result = null;
        try {
            result = sensitiveWordClient.addSensitiveWords(words.toArray(new String[words.size()]));
        } catch (Exception e) {
            log.error("极光敏感词添加失败:{}", e.getMessage());
            throw new RuntimeException("极光敏感词添加失败" + e.getMessage());
        }
        return result;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [newWord, oldWord]
     * @Author: huangpeng
     * @Date: 2021/10/25 10:14
     * @Description: 敏感词修改
     */
    public ResponseWrapper updateSensitiveWord(String newWord, String oldWord) {
        ResponseWrapper result = null;
        try {
            result = sensitiveWordClient.updateSensitiveWord(newWord, oldWord);
        } catch (Exception e) {
            log.error("极光敏感词修改失败:{}", e.getMessage());
            throw new RuntimeException("极光敏感词修改失败" + e.getMessage());
        }
        return result;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [word]
     * @Author: huangpeng
     * @Date: 2021/10/25 10:19
     * @Description: 删除敏感词
     */
    public ResponseWrapper deleteSensitiveWord(String word) {
        ResponseWrapper result = null;
        try {
            result = sensitiveWordClient.deleteSensitiveWord(word);
        } catch (Exception e) {
            log.error("极光敏感词删除失败:{}", e.getMessage());
            throw new RuntimeException("极光敏感词删除失败" + e.getMessage());
        }
        return result;
    }

    /**
     * @return cn.jmessage.api.sensitiveword.SensitiveWordListResult
     * @Param: [current, size]
     * @Author: huangpeng
     * @Date: 2021/10/25 10:19
     * @Description: 分页获取敏感词
     */
    public SensitiveWordListResult getSensitiveWordPage(Integer current, Integer size) {
        SensitiveWordListResult result = null;
        try {
            result = sensitiveWordClient.getSensitiveWordList(size * (current - 1), size);
        } catch (Exception e) {
            log.error("极光敏感词分页失败:{}", e.getMessage());
            throw new RuntimeException("极光敏感词分页失败" + e.getMessage());
        }
        return result;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [status]  1表示开启过滤， 0表示关闭敏感词过滤
     * @Author: huangpeng
     * @Date: 2021/10/25 10:22
     * @Description: 修改极光敏感词状态
     */
    public ResponseWrapper updateSensitiveWordStatus(Integer status) {
        ResponseWrapper result = null;
        try {
            result = sensitiveWordClient.updateSensitiveWordStatus(status);
        } catch (Exception e) {
            log.error("极光敏感词状态修改失败:{}", e.getMessage());
            throw new RuntimeException("极光敏感词状态修改失败" + e.getMessage());
        }
        return result;
    }

    /**
     * @return cn.jiguang.common.resp.ResponseWrapper
     * @Param: [status]
     * @Author: huangpeng
     * @Date: 2021/10/25 10:22
     * @Description: 获取极光敏感词状态
     */
    public SensitiveWordStatusResult getSensitiveWordStatus() {
        SensitiveWordStatusResult result = null;
        try {
            result = sensitiveWordClient.getSensitiveWordStatus();
        } catch (Exception e) {
            log.error("极光敏感词状态修改失败:{}", e.getMessage());
            throw new RuntimeException("极光敏感词状态修改失败" + e.getMessage());
        }
        return result;
    }

    //************************** 群消息
/**
* @Param: [fromUserId, toUserId, message]
* @return void
* @Author: huangpeng
* @Date: 2021/11/8 13:49
* @Description: 发送单个文本消息
*/
    public  void sendSingleTextByAdmin(String fromUserId,String toUserId,String message) {

        try {
            MessageBody body = MessageBody.text(message);
            SendMessageResult result = messageClient.sendSingleTextByAdmin(toUserId, fromUserId, body);
        } catch (Exception e) {
            log.error("极光消息发送异常:"+e.getMessage());
        }
    }

    /**
    * @Param: [fromUserId, toGroupId, message]
    * @return void
    * @Author: huangpeng
    * @Date: 2021/11/8 13:52
    * @Description: admin 给群发文本消息
    */
    public  void sendGroupTextByAdmin(String fromUserId,String toGroupId,String message,Map<String, String> extras) {

        try {
//            MessageBody body = MessageBody.newBuilder().setText(message).build();
            MessageBody body = MessageBody.text(message);
//            MessageBody body = new MessageBody(message,extras,null,null);
            SendMessageResult result = messageClient.sendGroupTextByAdmin(toGroupId, fromUserId, body);
            System.err.println("result"+result.toString());
        } catch (Exception e) {
            log.error("极光消息发送异常:"+e.getMessage());
        }
    }
    public  void sendGroupTextByUser(String fromUserId,String toGroupId,String message,Map<String, String> extras) {

        try {
            MessageBody body = MessageBody.newBuilder().setText(message).addExtras(extras).build();
            SendMessageResult sendMessageResult = messageClient.sendMessage(1, "group", toGroupId, "user", fromUserId, MessageType.TEXT, body);
            System.err.println("ddd"+sendMessageResult.toString());
        } catch (Exception e) {
            log.error("极光消息发送异常:"+e.getMessage());
        }
    }
}
